<template>
    <div>
        <div class="tag-and-button">
        <el-tag>代码编辑器</el-tag>
        <el-button type="primary" size="small" round icon="el-icon-video-play" @click="runCode()">运行</el-button>
        <el-button type="success" size="small" round icon="el-icon-finished" @click="submitUpdateChartData()">保存</el-button>
        <div class="button-container">
            <el-tag>图表渲染结果</el-tag>
            <el-button type="primary" icon="el-icon-edit" size="small" round @click="dialogVisible=true">修改信息</el-button>
        </div>
    </div>
        
        <div class="editor-container">
        <div class="json-editor"><textarea  ref="textarea"/></div>
        <div v-loading="chartLoading" style="border:1px solid #ccc;width:650px; height: 610px;" >
        <div ref="chartContainer" style="width: 650px; height: 610px;"></div>
        </div>
    </div>
    <el-dialog title="提示" :visible.sync="dialogVisible" width="60%">
  <div><el-form ref="updateForm" :model="updateForm" label-width="80px">
  <el-form-item label="图表名称">
    <el-input v-model="updateForm.name"></el-input>
  </el-form-item>
  <el-form-item label="图表结论">
    <el-input type="textarea" v-model="updateForm.result" :autosize="{ minRows: 6, maxRows: 8}"></el-input>
  </el-form-item>
</el-form></div>
  <span slot="footer" class="dialog-footer">
    <el-button @click="dialogVisible = false">取 消</el-button>
    <el-button type="primary" @click="submitUpdateChartInfo()">确 定</el-button>
  </span>
</el-dialog>
    </div>
</template>


<script>
// require styles
import 'codemirror/lib/codemirror.css'
// 引入语言
import 'codemirror/mode/javascript/javascript.js'
// 引入样式
import 'codemirror/theme/juejin.css'
import 'codemirror/theme/rubyblue.css'
import 'codemirror/theme/idea.css'
// JSON
import 'codemirror/addon/lint/lint.css'
import 'codemirror/addon/lint/json-lint'
import CodeMirror from 'codemirror'

//滚动条

import { queryByChartId,updateChartData,updateChartInfo} from '@/api/chart'
import * as echarts from 'echarts'
import chinaMap from '@/utils/china-main-city-map.json'
export default{
    name:'EditChart',
    data(){
        return{
        value: null, //这是option，即图表的配置信息
        jsonEditor:false,
        genResult:"",
        chartLoading:false,
        chartInfo:null,//这是chart的总信息
        dialogVisible:false,//对话框可见否
        chartType:"",
        chartId:null,
        updateForm:{
            name:"",//更新图表名称
            result:""//更新生成结论
        },
        }
    },
    created(){ 
      this.chartId=this.$route.params.id
      if(this.chartId) {sessionStorage.setItem("chartId",JSON.stringify(this.chartId))}
        queryByChartId({data:{chartId:JSON.parse(sessionStorage.getItem("chartId"))}}).then(response=>{
            this.chartInfo=response.data
            this.value=response.data.chartData
            this.updateForm.name=response.data.name
            this.updateForm.result=response.data.genResult
            this.chartType=response.data.chartType
            this.initEditor()
            this.dataClean(this.value)
            if (!this.chartInstance) {
                this.chartInstance = echarts.init(this.$refs.chartContainer);
            }
            //绘制出最近的图表
            this.handleOptionBeforeSet();
            this.chartInstance.setOption(this.decoration);
            })
    },
    methods: {
      handleOptionBeforeSet(){//一些额外处理，比如JSON中的函数
      if(this.chartType=="词云"){//处理下颜色
          this.decoration.series[0].textStyle.color=function() {
            var r = Math.floor(Math.random() * 256);
            var g = Math.floor(Math.random() * 256);
            var b = Math.floor(Math.random() * 256);
            return 'rgb(' + r + ',' + g + ',' + b + ')';
        };
        }else if(this.chartType=="关系图"){//标签转换
          this.decoration.legend[0].data=this.decoration.series[0].categories.map(function (a) {
          return a.name;
        })
        }else if(this.chartType=="地图"){
          echarts.registerMap('china',chinaMap)
        }
    },
    getValue () {
      return this.jsonEditor.getValue()
    },
    //初始化json编辑器
    initEditor() {
    this.jsonEditor = CodeMirror.fromTextArea(this.$refs.textarea, {
      lineNumbers: true,
      mode: 'application/json',
      gutters: ['CodeMirror-lint-markers'],
      theme: 'idea',
      lint: true,
    });

    // 设置编辑器值
    this.jsonEditor.setValue(this.value);
    console.log(this.value)
    this.jsonEditor.on('change', cm => {
      this.$emit('changed', cm.getValue());
      this.$emit('input', cm.getValue());
    });
    },
    //运行代码
    runCode(){
        let code = this.getValue()
        this.dataClean(code)
        console.log(this.chartType)
        this.handleOptionBeforeSet()
        this.chartInstance.setOption(this.decoration);
        //this.chartInstance.setOption(code)
    },
    //清洗数据
    dataClean(data){
        let cleanedData = data
        cleanedData = cleanedData.replace(/\/\/.*$/gm, '');
        cleanedData = cleanedData.replace(/^\s*\n*\"|\"\n*\s*$/g, '');
        cleanedData = cleanedData.replace(/\s+/g, ' ');
        cleanedData = cleanedData.replace(/javascript/g,'');
        cleanedData = cleanedData.replace(/\`{3}/g, '');
        cleanedData = cleanedData.replace(/;.*$/, ';')
        try{
            this.decoration=JSON.parse(cleanedData)//先解析为对象，然后后续进行处理
        }catch(error){
            this.$message.error('JSON解析错误,请检查你的代码');
        }
        
    },
    submitUpdateChartData(){
        this.$confirm('此操作将永久修改图表配置, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
            updateChartData({data:{chartId:this.chartInfo.id,chartData:this.getValue()}}).then(response=>{
                if(response.data===1){
                    this.$message({
                    type: 'success',
                    message: '修改成功!'
                });
                }else{
                    this.$message({
                    type: 'warning',
                    message: '修改失败!'
                });
                }
            })
        }).catch(() => {
          this.$message({
            type: 'info',
            message: '已取消更新'
          });          
        });
    },
    submitUpdateChartInfo(){
        this.$confirm('此操作将永久修改图表信息, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
            updateChartInfo({data:{chartId:this.chartInfo.id,chartName:this.updateForm.name,genResult:this.updateForm.result}}).then(response=>{
                if(response.data===1){
                    this.$message({
                    type: 'success',
                    message: '修改成功!'
                });
                this.dialogVisible=false
                }else{
                    this.$message({
                    type: 'warning',
                    message: '修改失败!'
                });
                }
            })
        }).catch(() => {
          this.$message({
            type: 'info',
            message: '已取消更新'
          });          
        });
    },
  }
}
</script>
<style scoped>
.button-container {
    display: flex;
    justify-content: center; /* 水平居中 */
    gap: 20px; /* 按钮之间的间隔 */
    margin-top: 10px; /* 距离图表的垂直间距 */
    margin-left:425px
}
.tag-and-button {
  display: flex;
  align-items: center;
  gap:20px;
  margin-top: 10px;
}
.editor-container {
    display: flex;
    gap: 20px; /* Add some space between the two elements */
}
.json-editor {
  width: 700px; /* 添加宽度设定 */
  height: 610px;
  position: relative;
  overflow: auto; 
  /* 以下代码用于美化滚动条 */
}
.json-editor >>> .CodeMirror {
  height: 100%;
  width: 100%; /* 确保CodeMirror填满其父元素 */
  min-height: initial; /* 移除min-height以避免固定最小高度干扰 */
  border: 2px solid #ccc; /* 添加边框，颜色和宽度可以根据需要调整 */
  border-radius: 3px; /* 可选，为边框添加圆角 */
}

</style>